package com.school.appleforgetbackend.util;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex; // 必须存在这行


public class YushanAES {

    public static void main(String[] args) {
        String aes_key = "XXX";//秘钥
        String content = "{\"req_data\":{\"cardNo\":\"37132xxxx77739\",\"name\":\"赵xx\"},\"req_time\":1578469155870,\"acct_id\":\"zshhxx_user\",\"inf_id\":\"P_C_B019\",\"prod_id\":\"P_C_B019\",\"request_sn\":\"20200108A2F7D406222E479BDC7h08RR\"}";

        try {
            String bbb = encode(content,aes_key);
            System.out.println("加密:"+bbb);
            System.out.println("解密:"+decode(bbb,aes_key));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //加密方法
    public static String encode(String content,String key) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(Hex.decodeHex(key.toCharArray()), "AES");
            System.out.println("skey:"+skeySpec);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");  //AESConstants.CIPHER_ALGORITHM_CBC
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec,new IvParameterSpec("0000000000000000".getBytes()));
            return Base64.encodeBase64String(cipher.doFinal(content.getBytes("UTF-8")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //解密方法
    public static String decode(String content,String key) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(Hex.decodeHex(key.toCharArray()), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");  //AESConstants.CIPHER_ALGORITHM_CBC
            cipher.init(Cipher.DECRYPT_MODE, skeySpec,new IvParameterSpec("0000000000000000".getBytes()));
            byte[] encryptAESResponseByte = Base64.decodeBase64(content);
            byte[] responseByte = cipher.doFinal(encryptAESResponseByte);
            return new String(responseByte);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
